// 日期和时间先不关函数
export default {
  /**
* 计算图片的大小
* @param {} limit
*/
  conver (limit) {
    let size = "";
    if (limit < 0.1 * 1024)
    {
      size = `${limit.toFixed(2)}B`;
    } else if (limit < 0.1 * 1024 * 1024)
    {
      size = `${(limit / 1024).toFixed(2)}KB`;
    } else if (limit < 0.1 * 1024 * 1024 * 1024)
    {
      size = `${(limit / (1024 * 1024)).toFixed(2)}MB`;
    } else
    {
      size = `${(limit / (1024 * 1024 * 1024)).toFixed(2)}GB`;
    }
    const sizestr = `${size}`;
    const len = sizestr.indexOf(".");
    const dec = sizestr.substr(len + 1, 2);
    if (dec === "00")
    {
      return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
    }
    return sizestr;
  },
  /**
   * 获取Cookie值 传入Cookie名称
   * @param name Cookie名称
   * @returns {string|boolean} 对应的name值
   */
  getCookie (name = null) {
    if (!name) return false;
    const strcookie = document.cookie; //获取cookie字符串
    const arrcookie = strcookie.split("; "); //分割
    //遍历匹配
    for (let i = 0; i < arrcookie.length; i++)
    {
      let arr = arrcookie[i].split("=");
      if (arr[0] === name)
      {
        return arr[1];
      }
    }
    return "";
  },

  /**
   * storage 加密存储类
   * @param {} params 
   * @returns  class applicationStorage
   */
  storage (params = {}) {
    class applicationStorage {
      /**
       * 
       * @param {key是否加密} key 
       *  @param {data是否加密} data 
       *  @param {存储的数据类 localStorage 还是 sessionStorage 默认 sessionStorage } type
       */
      constructor({ key = true, data = true, type = 'session' }) {
        this.isEncryptionKey = key;
        this.isEncryptionData = data;
        this.type = type;
      }
      /**
       * 加密数据
       * @param {any} data 转为base64数据
       */
      encrypt (data) {
        let set = encodeURIComponent(data), result = btoa(set);
        return result;
      }
      /**
       * 解码数据
       * @param {any} data 数据
       */
      MyLocker (data) {
        try
        {
          let jieMi = atob(data), jieM = decodeURIComponent(jieMi);
          return jieM;
        } catch (e)
        {
          throw Error('解码出错')
        }
      }
      /**
       *  根据参数区分存储对象
       * @param Session
       * @returns {Storage} 返回 Session 存储对象
       */
      isSession (Session) {
        return Session === 'local' ? localStorage : sessionStorage;
      }
      /**
       * 判断该当前的key 是否存在
       * @param key
       * @constructor
       */
      ISKET (key) {
        if (!key)
        {
          throw Error('请传入Session的KEY!!!')
        }
      }
      /**
       * Session存储方法
       * @param key 存储的key值
       * @param setObj 存储的数据
       * @param Session 存储 localStorage 还是 sessionStorage 默认 sessionStorage
       */
      setSession (key, setObj = {}) {
        this.ISKET(key);
        if (setObj instanceof Object && Object.keys(setObj).length > 0)
        {
          setObj = JSON.stringify(setObj);
        }

        this.isSession(this.type).setItem(this.isEncryptionKey ? this.encrypt(key) : key, this.isEncryptionData ? this.encrypt(setObj) : setObj);
      }
      /**
       * 获取存储的值
       * @param key 存储的key
       * @returns {any} 返回对应的key 的数据
       */
      getSession (key) {
        this.ISKET(key);

        let data = this.isSession(this.type).getItem(this.isEncryptionKey ? this.encrypt(key) : key);

        if (data && this.isEncryptionData)
        {
          try
          {
            return JSON.parse(this.isEncryptionData ? this.MyLocker(data) : data)
          } catch (e)
          {
            console.error('getSession方法获取数据错误', e);
            return false
          }
        } else
        {
          return JSON.parse(data)
        }
      }

      /**
       * 删除 指定单个key
       * @param key
       * @param Session
       */
      sessionClear (key) {
        this.ISKET(key);
        this.isSession(this.type).removeItem(this.isEncryptionKey ? this.encrypt(key) : key);
      }

      /**
       * 删除所有可以
       * @param Session
       */
      sessionClearAll () {
        this.isSession(this.type).clear();
      }
    }
    return new applicationStorage(params);
  },
  /**
  * 获取当前设备类型
  * 不传入阐述就返回 PC端 PCend || 移动端 mobile
  * 传入参数为移动端设备类型
  */
  /**
   * 
   * @param {传入'type'返回当前具体的设备类型,不传就 返回 PC端 PCend || 移动端 mobile'} type 
   * @returns 
   */
  getDeviceType (type = null) {
    let userAgentInfo = navigator.userAgent,
      flag, terminal = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod'];
    if (type)
    {
      for (let i in terminal)
      {
        if (userAgentInfo.includes(terminal[i]))
        {
          return terminal[i];
        }
      }
      return 'PCend';
    } else
    {
      for (let v = 0; v < terminal.length; v++)
      {
        if (userAgentInfo.indexOf(terminal[v]) > 0)
        {
          flag = 'mobile';
          break;
        }
      }
      return flag === 'mobile' ? 'mobile' : 'PCend';
    }
  },
  /**
   * 是否在微信客户端
   * @returns {boolean}
   */
  isWechatClient () {
    return navigator.userAgent.toLowerCase().includes('micromessenger') || navigator.userAgent.toLowerCase().match(/MicroMessenger/i) === "micromessenger"
  },

  /**
   * 安卓系统
   * @returns {boolean}
   */
  androidSystem () {
    let ua = navigator.userAgent;
    return ua.indexOf('Android') > -1 || ua.indexOf('Adr') > -1
  },

  /**
   * ios系统
   * @returns {boolean}
   */
  iosSystem () {
    let ua = navigator.userAgent;
    return !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
  },

  /**
   * 判断是否是pc
   * @returns {boolean} false 移动端页面 true pc端页面
   */
  isPc () {
    let ua = navigator.userAgent.toLowerCase();
    return /ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/.test(ua) ? false : true;
  },

  /**
   * 反调试
   * @param {*} ban 
   */
  debugging (ban) {
    let {
      Noright = true, NoKeyDown = true, debug = true
    } = ban || {};
    if (Noright)
    { //禁止鼠标右键
      this.onkeydown = this.onkeyup = this.onkeypress = function () {
        this.event.returnValue = false;
        return false;
      }
    }
    if (NoKeyDown)
    { //禁止F12
      let h = this.innerHeight,
        w = this.innerWidth;
      this.onresize = function () {
        if (h !== this.innerHeight || w !== this.innerWidth)
        {
          this.close();
          this.location = "about:blank";
        }
      }
    }
    if (debug)
    { //反调试代码
      ! function () {
        const handler = setInterval(() => {
          const before = new Date();
          debugger;
          const after = new Date();
          // 如果不打开调试模式的话,肯定不会大于100
          const cost = after.getTime() - before.getTime();
          if (cost > 100)
          {
            clearInterval(handler)
          }
        }, 1000)
      }();
    }
  },
  /**
   * 获取当前网络状态
   * @param {回调函数} cb 
   * @returns 
   */
  getNetwork (cb) {
    let connection = navigator.connection, type = connection.effectiveType;

    const getNet = () => {
      const { downlink, effectiveType, rtt } = navigator.connection,

        is = (Boolean(downlink) || Boolean(rtt)), isAvailable = is ? (is && navigator.onLine) : false;

      return {
        Details: { downlink, effectiveType, rtt },
        BeforeType: type, // 切换前的
        CurrentType: connection.effectiveType, // 切换后的
        Available: isAvailable // 当前网络是否可用
      }
    }
    // 监听网络切换
    connection.addEventListener('change', () => {
      cb instanceof Function && cb(getNet())
    });

    return getNet()
  },
  /**
   * 
   * @param {键盘按下回调函数} cb 
   */
  keyboard (cb) {
    document.onkeydown = (elevt) => {
      const { ctrlKey, shiftKey, altKey, keyCode } = elevt;
      //  e.ctrlKey   ctrl 
      // e.shiftKey	shift
      // e.altKey		
      // console.log(e);
      // if (ctrlKey && keyCode === 83)
      // {
      //   return false;
      // }

      cb instanceof Function && cb(ctrlKey, shiftKey, altKey, keyCode,)
    }
  },
  screnn () {
    return new (class screnn {

      constructor(data = { el: 'body', }) {

        const { el } = data;
        this.d = document;
        this.el = document.querySelector(el)

      }

      /**
       *
       * @param getInto 进入全屏时的回调函数
       * @param cb 自定义回调函数
       */
      LockMouse (getInto, cb) {

        let d = document;

        //进入全屏时触发
        const fullscreenChange = () => {

          if (d.webkitFullscreenElement === this.el || d.mozFullscreenElement === this.el || d.mozFullScreenElement === this.el)
          { // 较旧的 API 大写 'S'.
            // 元素进入全屏模式了，现在我们可以请求指针锁定。
            console.log(this.el);

            this.el.requestPointerLock = this.el.requestPointerLock || this.el.mozRequestPointerLock || this.el.webkitRequestPointerLock;
            this.el.requestPointerLock();
            getInto()
            console.log('全屏了')
          }
        }

        this.d.addEventListener('fullscreenchange', fullscreenChange(), false);
        this.d.addEventListener('mozfullscreenchange', fullscreenChange(), false);
        this.d.addEventListener('webkitfullscreenchange', fullscreenChange(), false);

        const pointerLockChange = () => {

          console.error(d.webkitPointerLockElement);

          if (d.mozPointerLockElement === this.el || d.webkitPointerLockElement === this.el)
          {
            console.log("指针锁定成功了。");
          } else
          {
            console.log("指针锁定已丢失。");
          }
        }

        this.d.addEventListener('pointerlockchange', pointerLockChange, false);
        this.d.addEventListener('mozpointerlockchange', pointerLockChange, false);
        this.d.addEventListener('webkitpointerlockchange', pointerLockChange, false);

        function pointerLockError () {
          console.log("锁定指针时出错。");
        }

        this.d.addEventListener('pointerlockerror', pointerLockError, false);
        this.d.addEventListener('mozpointerlockerror', pointerLockError, false);
        this.d.addEventListener('webkitpointerlockerror', pointerLockError, false);

      }


      /**
       * 退出全屏
       * @param cb 退出时的回调函数
       */
      close (cb) {
        let d = document;
        d.exitFullScreen ? d.exitFullScreen() : d.mozCancelFullScreen ? d.mozCancelFullScreen() : d.webkitExitFullscreen ? d.webkitExitFullscreen() : d.msExitFullscreen ? d.msExitFullscreen() : '';
      }


      open () {

        const $el = document.documentElement;
        const rfs = $el.requestFullScreen || $el.webkitRequestFullScreen || $el.mozRequestFullScreen || $el.msRequestFullscreen;
        if (typeof rfs != 'undefined' && rfs)
        {
          rfs.call($el);
        }
        return;
      }

    }
    )()
  },
  notice (params = {}, cb) {
    class alerts {
      constructor(datNotice = {}, cb = {}) {
        const { title = '标题', body = '内容', icon, image } = datNotice;
        if (!('Notification' in window)) { console.error('当前浏览器不支持通知'); }

        //通知显示授权状态的字符串
        //denied (用户拒绝了通知的显示), granted (用户允许了通知的显示), 或 default (因为不知道用户的选择，所以浏览器的行为与 denied 时相同)
        if (Notification.permission !== 'granted') console.error('请同意浏览器通知,正式环境使用HTTPS域名，否则无法弹出权限，本地开发请使用localhost 打开地址');

        Notification.requestPermission(status => {
          // 同意了通知
          if (status === 'granted')
          {
            let notify = new Notification(`${title || '通知'}`, {

              actions: [],
              badge: "111111",
              body,
              data: 3000,
              dir: "auto",
              icon,
              image,
              lang: "",
            })

            // 桌面消息显示时
            notify.onshow = (e) => {
              // let audio = new Audio('./mp3/test2.mp3');
              // audio.play();
              console.log('桌面消息显示时', e)
              cb.show instanceof Function && cb.show()

            }
            // 点击时桌面消息时触发
            notify.onclick = (e) => {
              // 跳转到当前通知的tab,如果浏览器最小化，会将浏览器显示出来
              console.log('点击时桌面消息时触发', e)
              cb.click instanceof Function && cb.click()
              window.focus()
            }
            notify.onclose = (e) => {
              console.log('点击时桌面关闭触发', e)
            }
            notify.onerror = (e) => {
              console.log('错误时触发', e)
            }
            console.log(notify);
          }
        })
      }
    }
    return new alerts(params, cb)
  }
}